package org.om.dao;


import org.om.excepion.BusinessException;
import org.om.model.Users;
import org.redkale.service.Service;
import org.redkale.source.DataSource;
import org.redkale.util.AutoLoad;
import org.redkale.util.ResourceType;
import org.redkale.util.Utility;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * The type User dao.
 *
 * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
 * @date :2016-07-01 14:46:04
 */
@ResourceType({UserDao.class})
public class UserDao implements Service{
    /**
     * The Source.
     *
     * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
     * @date :2016-07-01 14:48:53
     */
    @Resource
    protected DataSource source;

    /**
     * Get by id users.
     *
     * @param id the id
     * @return the users
     * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
     * @date :2016-07-01 14:48:53
     */
    public Users getById(int id){
        try{
            Users user =  source.find(Users.class,id);
            return user;
        }catch (Exception e){
           e.printStackTrace();
            return null;
        }
    }

    /**
     * Get by login name users.
     *
     * @param loginName the login name
     * @return the users
     * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
     * @date :2016-07-01 14:57:48
     */
    public Users getByLoginName(String loginName){
        return  source.find(Users.class,"loginName",loginName);
    }

    /**
     * Save.
     *
     * @param user the user
     * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
     * @date :2016-07-01 14:57:48
     */
    public void save(Users user) throws BusinessException {
        String pwd =  user.getLoginPwd();
        String md5pwd = null;
        /*try {
            md5pwd = md5IfNeed(pwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw  new BusinessException("密码转换出错！");
        }*/
        Users blUser =  getByLoginName(user.getLoginName());
        if(blUser!=null){
            throw  new BusinessException("用户名已经存在！");
        }
        user.setLoginPwd(md5pwd);
        source.insert(user);
    }


    /**
     * Update.
     *
     * @param user the user
     * @author :<a href="mailto:penggangshu@ebnew.com">舒彭钢</a>
     * @date :2016-07-01 14:58:15
     */
    public void update (Users user){
        source.update(user);
    }


/*    private static String md5IfNeed(String password) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = password.trim().getBytes();
        synchronized (md5) {
            bytes = md5.digest(bytes);
        }
        return new String(Utility.binToHex(bytes));
    }*/


}
